package com.furentech.iotserver.fa.sinopec.sinopec_processor;

import com.furentech.iotserver.fa.sinopec.SinopecFunCode;
import com.furentech.iotserver.fa.sinopec.SinopecRestRequest;
import com.furentech.iotserver.fa.utils.HexStringUtils;
import io.netty.channel.Channel;
import lombok.Data;
import org.springframework.stereotype.Component;

@Data
class AuthReq1
{
    public AuthReq1() {
        POS_TTC = new byte[4];
        MAC = new byte[4];
        ASN = new byte[10];

    }

    byte NZN;
    byte[] POS_TTC;
    String DispenserT_IME;
    byte Pay_X;
    int PRC;
    int BAL;
    String Add_ons;
    String PIN_block;
    int AMN;
    int VOL;
    byte[] ASN;
    String VehiclePlate;
    String LimitGrade;
    byte[] MAC;
}

@Component
public class AuthReq1_Processor extends SinopecProcessorBase{

    AuthReq1  decodeFormBytes(byte[] buf) {
        AuthReq1 authReq1 = new AuthReq1();

        authReq1.setNZN(buf[1]);
        System.arraycopy(buf, 2, authReq1.POS_TTC, 0, 4);
        authReq1.setPay_X(buf[13]);
        authReq1.setPRC((0x00ff & buf[14]) * 256 + (0x00ff & buf[15]));
        authReq1.setAMN((0x00ff & buf[66]) * 65536 + (0x00ff & buf[67]) * 256 + (0x00ff & buf[68]));
        authReq1.setVOL((0x00ff & buf[69]) * 65536 + (0x00ff & buf[70]) * 256 + (0x00ff & buf[71]));
        System.arraycopy(buf, 72, authReq1.ASN, 0, 10);
        System.arraycopy(buf, 100, authReq1.MAC, 0, 4);

        return  authReq1;
    }

    @Override
    String actualGetJsonString(byte[] buf) {
        return null;
    }

    @Override
    String actualGetReadableString(byte[] buf) {
        return "加油卡授权请求";
    }

    @Override
    byte[] actualGetResponse(byte[] buf, Channel channel) {

        AuthReq1 authReq1 = decodeFormBytes(buf);

        byte[] responseBuf = new byte[30];

        responseBuf[0]=SinopecFunCode.Auth_FB & 0x00ff;
        responseBuf[1] = authReq1.getNZN();
        System.arraycopy(authReq1.POS_TTC, 0, responseBuf, 2, 4);
        responseBuf[6] = authReq1.getPay_X();
        responseBuf[7] = (byte) (0x00ff & (authReq1.getPRC() / 256));
        responseBuf[8] = (byte) (0x00ff & (authReq1.getPRC() % 256));

        responseBuf[9]=2;
        responseBuf[10]='O';
        responseBuf[11] = 'K';

        responseBuf[12]=(byte) (0x00ff & (authReq1.getAMN() / 65536));
        responseBuf[13]=(byte) (0x00ff & (authReq1.getAMN() / 256));
        responseBuf[14] = (byte) (0x00ff & (authReq1.getAMN() % 256));

        System.arraycopy(authReq1.getASN(), 0, responseBuf, 15, 10);

        if (SinopecRestRequest.getFuelCardAbility(HexStringUtils.toHexString(authReq1.ASN, 0, 10))) {
            responseBuf[25] = 0x01;
        } else {
            responseBuf[25] = 0x03;
        }

        System.arraycopy(authReq1.MAC, 0, responseBuf, 26, 4);

        return responseBuf;
    }
}
